<template>
  <div class="edit-post-container">
    <div class="edit-header">
      <h1>编辑文章</h1>
      <div class="header-actions">
        <a-space>
          <a-button @click="handleSaveDraft" :loading="draftLoading">
            保存草稿
          </a-button>
          <a-button 
            type="primary" 
            @click="handleUpdate"
            :loading="updateLoading"
          >
            更新文章
          </a-button>
        </a-space>
      </div>
    </div>

    <a-spin :spinning="loading">
      <a-form
        v-if="formData"
        :model="formData"
        :rules="rules"
        @finish="handleUpdate"
        layout="vertical"
        class="edit-form"
      >
        <a-form-item label="文章标题" name="title">
          <a-input
            v-model:value="formData.title"
            placeholder="请输入文章标题"
            size="large"
            class="title-input"
          />
        </a-form-item>

        <a-form-item label="文章摘要" name="excerpt">
          <a-textarea
            v-model:value="formData.excerpt"
            placeholder="请输入文章摘要（可选）"
            :rows="3"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="文章内容" name="content">
          <div class="editor-container">
            <a-textarea
              v-model:value="formData.content"
              placeholder="开始写作吧..."
              :rows="20"
              class="content-editor"
            />
          </div>
        </a-form-item>

        <a-form-item label="文章标签" name="tagIds">
          <a-select
            v-model:value="formData.tagIds"
            mode="multiple"
            placeholder="添加标签"
            :options="tagOptions"
            class="tags-select"
          />
        </a-form-item>

        <a-form-item label="文章分类" name="categoryId">
          <a-select
            v-model:value="formData.categoryId"
            placeholder="选择分类"
            :options="categoryOptions"
            class="category-select"
          />
        </a-form-item>

        <a-form-item label="发布设置">
          <a-space direction="vertical" style="width: 100%">
            <a-checkbox v-model:checked="formData.isPublic">
              公开文章（其他人可以查看）
            </a-checkbox>
            <a-checkbox v-model:checked="formData.allowComments">
              允许评论
            </a-checkbox>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { postApi, categoryApi, tagApi } from '@/api'
import type { Post, Category, Tag } from '@/types'

const route = useRoute()
const router = useRouter()
const postId = Number(route.params.id)

// 响应式数据
const loading = ref(false)
const draftLoading = ref(false)
const updateLoading = ref(false)
const formData = ref<any>(null)
const categories = ref<Category[]>([])
const tags = ref<Tag[]>([])

// 计算属性：标签选项
const tagOptions = computed(() => {
  return tags.value.map(tag => ({
    label: tag.name,
    value: tag.id
  }))
})

// 计算属性：分类选项
const categoryOptions = computed(() => {
  return categories.value.map(category => ({
    label: category.name,
    value: category.id
  }))
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在5到100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '文章内容至少10个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ]
}

// 加载文章数据
const loadPostData = async () => {
  loading.value = true
  
  try {
    // 并行加载文章详情、分类和标签数据
    const [postResponse, categoriesResponse, tagsResponse] = await Promise.all([
      postApi.getPostDetail(postId),
      categoryApi.getCategoryList({ page: '1', size: '100' }),
      tagApi.getTagList({ pageNo: '1', pageSize: '100' })
    ])
    
    // 设置文章数据
    const post = postResponse.data
    formData.value = {
      title: post.title,
      excerpt: post.excerpt,
      content: post.content,
      tagIds: post.tags?.map(tag => tag.id) || [],
      categoryId: post.categoryId,
      isPublic: post.status === 'PUBLISHED',
      allowComments: true // 默认允许评论
    }
    
    // 设置分类和标签数据
    categories.value = categoriesResponse.data.result || []
    tags.value = tagsResponse.data.result || []
  } catch (error) {
    message.error('加载文章数据失败')
    router.push('/')
  } finally {
    loading.value = false
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!formData.value) return
  
  draftLoading.value = true
  
  try {
    const postData = {
      ...formData.value,
      status: 'DRAFT'
    }
    
    await postApi.updatePost(postId, postData)
    message.success('草稿保存成功')
  } catch (error) {
    message.error('保存草稿失败')
  } finally {
    draftLoading.value = false
  }
}

// 更新文章
const handleUpdate = async () => {
  if (!formData.value) return
  
  updateLoading.value = true
  
  try {
    const postData = {
      ...formData.value,
      status: formData.value.isPublic ? 'PUBLISHED' : 'DRAFT'
    }
    
    await postApi.updatePost(postId, postData)
    message.success('文章更新成功！')
    router.push(`/post/${postId}`)
  } catch (error) {
    message.error('更新失败，请重试')
  } finally {
    updateLoading.value = false
  }
}

onMounted(() => {
  loadPostData()
})
</script>

<style scoped>
.edit-post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.edit-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.edit-form {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title-input {
  font-size: 18px;
  font-weight: 500;
}

.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.content-editor {
  border: none;
  resize: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.6;
}

.content-editor:focus {
  box-shadow: none;
}

.tags-select,
.category-select {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-post-container {
    padding: 16px;
  }
  
  .edit-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .edit-form {
    padding: 20px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .header-actions .ant-space {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>